package com.zjj.edu.web.controller.system;

import com.zjj.edu.common.annotation.Log;
import com.zjj.edu.common.constant.UserConstants;
import com.zjj.edu.common.core.controller.BaseController;
import com.zjj.edu.common.core.domain.AjaxResult;
import com.zjj.edu.common.core.page.TableDataInfo;
import com.zjj.edu.common.core.text.Convert;
import com.zjj.edu.common.enums.BusinessType;
import com.zjj.edu.common.utils.poi.ExcelUtil;
import com.zjj.edu.framework.util.ShiroUtils;
import com.zjj.edu.framework.util.UserPermissionUtil;
import com.zjj.edu.system.domain.SysCourse;
import com.zjj.edu.system.domain.SysCourseGoods;
import com.zjj.edu.system.domain.SysTeachGoods;
import com.zjj.edu.system.domain.SysUser;
import com.zjj.edu.system.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 课程Controller
 *
 * @author zjj
 * @date 2020-06-30
 */
@Controller
@RequestMapping("/teach/course")
public class SysCourseController extends BaseController
{
    private String prefix = "teach/course";

    @Autowired
    private ISysCourseService sysCourseService;

    @Autowired
    private ISysTenantService tenantService;

    @Autowired
    private ISysSubjectService subjectService;

    @Autowired
    private ISysGradeService gradeService;

    @Autowired
    private ISysTeachGoodsService sysTeachGoodsService;

    @RequiresPermissions("teach:course:view")
    @GetMapping()
    public String course(ModelMap mmap)
    {
        mmap.put("subjectList", subjectService.selectAllSysSubjectList(ShiroUtils.getTenantId()));
        mmap.put("gradeList", subjectService.selectAllSysSubjectList(ShiroUtils.getTenantId()));
        return prefix + "/course";
    }

    /**
     * 查询课程列表
     */
    @RequiresPermissions("teach:course:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysCourse sysCourse)
    {
        startPage();
        sysCourse.setTenantId(ShiroUtils.getTenantId());
        List<SysCourse> list = sysCourseService.selectSysCourseList(sysCourse);
        return getDataTable(list);
    }

    /**
     * 导出课程列表
     */
    @RequiresPermissions("teach:course:export")
    @Log(title = "课程", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysCourse sysCourse)
    {
        sysCourse.setTenantId(ShiroUtils.getTenantId());
        List<SysCourse> list = sysCourseService.selectSysCourseList(sysCourse);
        ExcelUtil<SysCourse> util = new ExcelUtil<SysCourse>(SysCourse.class);
        return util.exportExcel(list, "course");
    }

    /**
     * 新增课程
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        long tenantId = ShiroUtils.getTenantId();
        mmap.put("subjectList", subjectService.selectAllSysSubjectList(tenantId));
        mmap.put("gradeList", gradeService.selectAllSysGradeList(tenantId));
        return prefix + "/add";
    }

    /**
     * 新增保存课程
     */
    @RequiresPermissions("teach:course:add")
    @Log(title = "课程", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysCourse sysCourse)
    {
        sysCourse.setTenantId(ShiroUtils.getTenantId());
        if (UserConstants.NAME_NOT_UNIQUE.equals(sysCourseService.checkNameUnique(sysCourse))) {
            return error("新增'" + sysCourse.getName() + "'失败，名称已存在");
        }
        sysCourse.setCreateBy(ShiroUtils.getLoginName());
        int status = sysCourseService.insertSysCourse(sysCourse);
        if (status > 0) {
            List<SysCourseGoods> list = new ArrayList();
            String[] ids = sysCourse.getIds();
            if (ids != null && ids.length > 0) {
                for (String goodsId : ids) {
                    SysCourseGoods goods = new SysCourseGoods();
                    goods.setCourseId(sysCourse.getId());
                    goods.setGoodsId(Long.parseLong(goodsId));
                    list.add(goods);
                }
                sysCourseService.insertSysCourseGoods(list);
            }
        }
        return toAjax(status);
    }

    /**
     * 校验名称
     */
    @PostMapping("/checkNameUnique")
    @ResponseBody
    public String checkTenantNameUnique(SysCourse sysCourse) {
        sysCourse.setTenantId(ShiroUtils.getTenantId());
        return sysCourseService.checkNameUnique(sysCourse);
    }

    /**
     * 修改课程
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        long tenantId = ShiroUtils.getTenantId();
        mmap.put("subjectList", subjectService.selectAllSysSubjectList(tenantId));
        mmap.put("gradeList", gradeService.selectAllSysGradeList(tenantId));
        mmap.put("sysCourse", sysCourseService.selectSysCourseById(id));
        List<SysCourseGoods> list = sysTeachGoodsService.selectSysCourseGoodsById(id);
        if (CollectionUtils.isNotEmpty(list)) {
            String ids = "";
            for (SysCourseGoods s: list) {
                long goodsId = s.getGoodsId();
                ids += goodsId + ",";
            }
            mmap.put("ids", ids.substring (0, ids.length() - 1));
        }
        return prefix + "/edit";
    }

    /**
     * 修改保存课程
     */
    @RequiresPermissions("teach:course:edit")
    @Log(title = "课程", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysCourse sysCourse)
    {
        sysCourse.setTenantId(ShiroUtils.getTenantId());
        if (UserConstants.NAME_NOT_UNIQUE.equals(sysCourseService.checkNameUnique(sysCourse))) {
            return error("修改课程'" + sysCourse.getName() + "'失败，名称已存在");
        }
        sysCourse.setUpdateBy(ShiroUtils.getLoginName());
        int status = sysCourseService.updateSysCourse(sysCourse);
        if (status > 0) {
            long courseId = sysCourse.getId();
            List<SysCourseGoods> dbList = sysTeachGoodsService.selectSysCourseGoodsById(courseId);
            if (CollectionUtils.isNotEmpty(dbList)) {
                sysTeachGoodsService.removeCourseGoods(courseId);
            }

            List<SysCourseGoods> list = new ArrayList();
            String[] ids = sysCourse.getIds();
            if (ids != null && ids.length > 0) {
                for (String goodsId : ids) {
                    SysCourseGoods goods = new SysCourseGoods();
                    goods.setCourseId(courseId);
                    goods.setGoodsId(Long.parseLong(goodsId));
                    list.add(goods);
                }
                sysCourseService.insertSysCourseGoods(list);
            }
        }
        return toAjax(status);
    }

    /**
     * 删除课程
     */
    @RequiresPermissions("teach:course:remove")
    @Log(title = "课程", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        SysUser user = ShiroUtils.getSysUser();
        SysCourse course = new SysCourse();
        course.setIds(Convert.toStrArray(ids));
        course.setUpdateBy(user.getUserName());
        if (!UserPermissionUtil.checkUserPermiss()) {
            course.setTenantId(user.getTenantId());
        }
        return toAjax(sysCourseService.deleteSysCourseByIds(course));
    }

    /**
     * 状态修改
     */
    @Log(title = "课程管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("teach:course:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysCourse sysCourse)
    {
        sysCourse.setTenantId(ShiroUtils.getTenantId());
        return toAjax(sysCourseService.updateSysCourse(sysCourse));
    }

    /**
     *
     * @param mmap
     * @return
     */
    @GetMapping("/searchGoods")
    public String searchGoods(String ids, ModelMap mmap)
    {
        mmap.put("ids", ids);
        return prefix + "/searchGoods";
    }

    @PostMapping("/toLoadGoods")
    @ResponseBody
    public TableDataInfo toSelectGoods(String ids)
    {
        SysTeachGoods goods = new SysTeachGoods();
        goods.setTenantId(ShiroUtils.getTenantId());
        goods.setIds(Convert.toStrArray(ids));
        List<SysTeachGoods> list = sysTeachGoodsService.selectSysTeachGoodsListByIds(goods);
        return getDataTable(list);
    }
}
